package com.shujia.flink.core

import com.shujia.flink.core.Demo3EventTime.Event
import org.apache.flink.streaming.api.TimeCharacteristic
import org.apache.flink.streaming.api.scala._
import org.apache.flink.streaming.api.windowing.assigners.{EventTimeSessionWindows, ProcessingTimeSessionWindows}
import org.apache.flink.streaming.api.windowing.time.Time

object Demo5SessionWindow {
  def main(args: Array[String]): Unit = {
    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    env.setParallelism(1)

    //指定时间模式为事件时间
    //默认是处理时间
    env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime)


    val lineDS: DataStream[String] = env.socketTextStream("master", 8888)


    val events: DataStream[Event] = lineDS.map(line => Event(line.split(",")(0), line.split(",")(1).toLong))


    /**
      * 会话窗口： 隔一段时间没有数据开始计算
      * ProcessingTimeSessionWindows: 处理时间的会话窗口
      * EventTimeSessionWindows： 事件时间的会话窗口，中间间隔超时一段时间
      *
      */

    events
      .assignAscendingTimestamps(_.ts)
      .map(e => (e.id, 1))
      .keyBy(_._1)
      .window(EventTimeSessionWindows.withGap(Time.seconds(10)))
      .sum(1)
      .print()


    env.execute()


  }

}
